package com.lingyuan.discounts.tactics.impl;

import com.lingyuan.common.core.domain.vo.cart.CartItemVo;
import com.lingyuan.common.core.domain.vo.sms.CouponSkuIdsVo;
import com.lingyuan.common.core.domain.vo.sms.SkuCouponPrice;
import com.lingyuan.discounts.tactics.DiscountStrategy;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName：PayNumFixedDiscountStrategy
 * @Author: LeiHao
 * @Date: 2024/10/3 9:20
 * @Description: 按照固定金额折扣
 */
@Component("payNumFixedDiscount")
public class PayNumFixedDiscountStrategy implements DiscountStrategy {

    @Override
    public CouponSkuIdsVo calculateDiscount(List<CartItemVo> cartItemVoList,String amount) {
        //同价格
        BigDecimal totalPrice = cartItemVoList.stream().map(CartItemVo::getTotalPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
        Integer paySumNum = cartItemVoList.stream().map(CartItemVo::getPayNum).reduce(0, Integer::sum);
        String[] amountList = amount.split("\\|");
        //使用门槛
        Integer payNum = Integer.valueOf(amountList[0]);
        //优惠价格
        BigDecimal discount = new BigDecimal(amountList[1]);
        if (payNum>paySumNum){
            //不满足使用门槛
            return null;
        }
        CouponSkuIdsVo couponSkuIdsVo = new CouponSkuIdsVo();
        //优惠后价格
        BigDecimal multiply = totalPrice.subtract(discount);
        couponSkuIdsVo.setTotalPrice(multiply);
        //优惠价格
        couponSkuIdsVo.setCouponPrice(discount);
        //计算每一个商品优惠价格
        List<SkuCouponPrice> skuCouponPriceList = cartItemVoList.stream().map(cartItem -> {
            SkuCouponPrice skuCouponPriceVo = new SkuCouponPrice();
            skuCouponPriceVo.setSkuId(cartItem.getProductId());
            // 使用 MathContext 指定除法运算的精度
            MathContext mc = new MathContext(2, RoundingMode.HALF_UP);  // 这里设置保留2位小数
            //商品优惠价格
            BigDecimal skuCouponPrice = discount.multiply(cartItem.getTotalPrice().divide(totalPrice,mc));
            skuCouponPriceVo.setCouponPrice(skuCouponPrice);
            //优惠后价格
            skuCouponPriceVo.setTotalPrice(cartItem.getTotalPrice().subtract(skuCouponPrice));
            return skuCouponPriceVo;
        }).collect(Collectors.toList());
        couponSkuIdsVo.setSkuCouponPriceList(skuCouponPriceList);
        return couponSkuIdsVo;
    }
}
